<template>
  <div class="search-suggestion">
    <van-cell
      v-for="(str,index) in suggestions"
      :key="index"
      icon="search"
      @click="$emit('search', str)">
      <div slot="title" v-html="highlight(str)"></div>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggestions } from '@/api/search.js'
import { debounce } from 'lodash'
export default {
  name: 'SearchSuggestion',
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  components: {},
  data () {
    return {
      suggestions: []
    }
  },
  computed: {},
  watch: {
    searchText: {
      handler: debounce(async function () {
        const { data } = await getSearchSuggestions(this.searchText)
        this.suggestions = data.data.options
      }, 200),
      immediate: true
    }
  },
  methods: {
    highlight (str) {
      const replaceStr = `<span style="color: red">${this.searchText}</span>`
      const reg = new RegExp(this.searchText, 'gi')
      return str.replace(reg, replaceStr)
    }
  },
  created () {
  },
  mounted () {
  },
  destroyed () {
  }
}
</script>

<style scoped lang='less'>
</style>
